<template>
  <div style="border: 1px solid #ccc">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      style="height: 500px; overflow-y: hidden"
      v-model="localValue"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
      @update:modelValue="onUpdate"
    />
  </div>
</template>

<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css'; // 引入 css

import { onBeforeUnmount, ref, shallowRef, watch, defineProps, defineEmits } from 'vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';

// v-model 双向绑定
const props = defineProps<{ modelValue: string }>();
const emits = defineEmits(['update:modelValue']);
const localValue = ref(props.modelValue ?? '');
watch(
  () => props.modelValue,
  (val: string) => {
    if (val !== localValue.value) localValue.value = val;
  }
);
const onUpdate = (val: string) => {
  localValue.value = val;
  emits('update:modelValue', val);
};

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
// 编辑器模式，默认 'default'，还有 'simple'
const mode = ref('default');

const toolbarConfig = {};
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      server: '/api/file/upload',
      fieldName: 'file',
      // 支持多图上传
      maxFileSize: 5 * 1024 * 1024, // 5MB
      maxNumberOfFiles: 10,
      allowedFileTypes: ['image/*'],
      // 自定义插入图片
      customInsert(res: any, insertFn: Function) {
        // 假设后端返回 { url: '图片地址', ... }
        if (res && res.url) {
          insertFn(res.url);
        } else if (res.data && res.data.url) {
          insertFn(res.data.url);
        } else {
          // 可根据实际返回结构调整
          insertFn('');
        }
      },
      // 可选：自定义 headers
      headers: {
        // Authorization: 'Bearer xxx',
      }
    }
  }
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor === null) return;
  editor.destroy();
});

const handleCreated = (editor: any) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};
</script>

<style scoped></style>
